package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.base.query.QueryObject;
import cn.wolfcode.car.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class StatementItemServiceImpl implements IStatementItemService {
    @Resource
    private StatementItemMapper statementItemMapper;
    @Resource
    private StatementServiceImpl statementService;

    @Override
    public StatementItem get(Long id) {
        return statementItemMapper.selectOne(id);
    }

    @Override
    public TablePageInfo<StatementItem> query(QueryObject qo, Long statementId) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(statementItemMapper.queryForList(qo, statementId));
    }

    @Override
    @Transactional
    public void save(List<StatementItem> items) {
        // 删除并获取最后一条记录
        StatementItem remove = items.remove(items.size() - 1);
        // 获取结算单对象
        Long statementId = remove.getStatementId();
        Statement statement = statementService.queryById(statementId);
        // 获取优惠价格
        BigDecimal itemPrice = remove.getItemPrice();
        // 合理性判断
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("只有状态为消费中的结算单才能保存");
        }
        // 删除明细项的集合
        statementItemMapper.deleteByStatementId(statementId);
        // 总价格和总数量
        BigDecimal totalAmount = new BigDecimal("0.00");
        BigDecimal totalQuantity = new BigDecimal("0");
        // 统计明细的金额和数量
        for (StatementItem item : items) {
            totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
            totalQuantity = totalQuantity.add(item.getItemQuantity());
        }
        // 判断折扣金额的合理性
        if (totalAmount.compareTo(itemPrice) < 0) {
            throw new BusinessException("折扣金额不合理");
        }
        // 批量添加数据
        statementItemMapper.insertBatch(items);
        // 更新结算单的数据
        statementService.updateAmount(totalAmount, totalQuantity, itemPrice, statementId);
    }

    @Override
    @Transactional
    public void update(StatementItem statementItem) {
        statementItemMapper.update(statementItem);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        statementItemMapper.deleteById(id);
    }
}
